<template>
	<view class="bg-[#FFFFFF] px-[16px]">
		<u-form ref="formRef" labelPosition="left" label-width="100px" borderBottom :rules="rules" :model="formData">
			<u-form-item label="收货人" prop="LinkMan">
				<u-input v-model="formData.LinkMan" border="none" placeholder="请输入收货人姓名" clearable></u-input>
			</u-form-item>
			<u-form-item label="手机号码" prop="Mobile">
				<u-input v-model="formData.Mobile" placeholder="请输入收货人手机号码" border="none" clearable
					type="number"></u-input>
			</u-form-item>
			<u-form-item @click="showArea()" label="所在城市" prop="AreaStr">
				<u-input :customStyle="{pointerEvents: 'none'}" disabled v-model="formData.AreaStr" border="none"
					placeholder="请选择所在城市" disabledColor="transparent"></u-input>
				<u-icon v-slot:right name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="收货详细地址" prop="Street">
				<u-input v-model="formData.Street" border="none" placeholder="请输入门牌号" clearable></u-input>
			</u-form-item>
			<u-form-item label="是否默认地址" prop="IsDefault">
				<u-switch v-model="formData.IsDefault" :activeValue="1" :inactiveValue="0"></u-switch>
			</u-form-item>
		</u-form>
	</view>
	<u-gap height="60"></u-gap>
	<u-button @click="save" class="mx-[16px]" text="保存收货地址" size="large" shape="circle" type="error"></u-button>
	<template v-if="mode == 'edit'">
		<u-gap height="20"></u-gap>
		<u-button @click="del" class="mx-[16px]" text="删除收货地址" size="large" shape="circle" color="rgb(191,191,191)"></u-button>
	</template>
	<u-picker @confirm="confirmHandler" :columns="columns" :show="areaShow" @cancel="closeArea()" @change="changeHandler"></u-picker>
</template>

<script setup>
	import { nextTick, ref, unref } from "vue";
	import * as api from "@/api.js";
	import * as uniapp from "@dcloudio/uni-app";
	import { useUserStore } from "@/store/config.js";

	const store = useUserStore();

	const mode = ref('add');
	const formRef = ref();
	const formData = ref({
		LinkMan: '',
		Street: '',
		Mobile: '',
		IsDefault: 0,
		AddressID: '',
		AreaID: '',
		AreaStr: ''
	})
	const rules = {
		LinkMan: {
			type: 'string',
			required: true,
			message: '请填写姓名',
			trigger: 'blur'
		},
		Mobile: [{
			required: true,
			message: '请填写手机号码',
			trigger: 'blur'
		}, {
			validator: (rule, value, callback) => {
				return uni.$u.test.mobile(value);
			},
			message: '手机号码不正确',
			// 触发器可以同时用blur和change
			trigger: 'blur',
		}],
		AreaStr: {
			type: 'string',
			required: true,
			message: '请选择省市区',
			trigger: 'blur'
		},
		Street: {
			type: 'string',
			required: true,
			message: '请填写详细地址',
			trigger: 'blur'
		}
	}

	const areaShow = ref(false);
	const showArea = () => {
		areaShow.value = true
	}
	const closeArea = () => {
		areaShow.value = false
	}
	
	const columns = ref([ [], [], [] ]);
	
	const strs = ref();
	
	const changeHandler = (e) => {
		const {
			columnIndex,
			value,
			values,
			indexs,
			index,
			picker
		} = e;
		if(columnIndex == 0) {
			const r = strs.value[index].children.map(i => {
				return {
					text:i.label,
					value:i.value
				}
			});
			picker.setColumnValues(1,r);
			const r2 = strs.value[index].children[0]?.children.map(i => {
				return {
					text:i.label,
					value:i.value
				}
			}) || [];
			picker.setColumnValues(2,r2);
		} else {
			const r2 = strs.value[indexs[0]].children[indexs[1]]?.children.map(i => {
				return {
					text:i.label,
					value:i.value
				}
			}) || [];
			picker.setColumnValues(2,r2);
		}
	};
	
	const confirmHandler = e => {
		const reversedArr=e.value.filter(i=>!!i);
		const result = reversedArr.reverse();
		formData.value.AreaID = result[0].value;
		//console.log(result[0].value);
		formData.value.AreaStr = reversedArr.reverse().map(i => i.text).join('');
		closeArea();
	}

	const getArea = async () => {
		uni.showLoading();
		const result = await api.getAreaJson();
		uni.hideLoading();
		if (result[0]) {
			const str = JSON.parse(result[0]);
			strs.value = str;
			columns.value[0] = str.map(i => {
				return {
					text:i.label,
					value:i.value
				}
			})
			columns.value[1] = str[0].children.map(i => {
				return {
					text:i.label,
					value:i.value
				}
			})
			columns.value[2] = str[0].children[0]?.children.map(i => {
				return {
					text:i.label,
					value:i.value
				}
			}) || []
			//console.log(columns.value)
		}
	}

	uniapp.onLoad(option => {
		mode.value = option.mode
		if (option.mode == 'edit') {
			formData.value = JSON.parse(decodeURIComponent(option.data))
			uni.setNavigationBarTitle({
				title: '编辑收货地址'
			})
		} else {
			uni.setNavigationBarTitle({
				title: '新增收货地址'
			})
		}
		getArea();
	})
	
	const save = () => {
		formRef.value.validate().then(async res => {
			uni.showLoading();
			const result = await api.addAddress(store.user.UserID,unref(formData));
			uni.hideLoading();
			await nextTick();
			if(result[1]) {
				uni.showToast({
					icon:'none',
					title:result[1]
				})
			} else {
				uni.showToast({
					icon:'success',
					title:formData.value.AddressID ? '修改成功' : '添加成功'
				})
				await uni.$u.sleep(800);
				uni.navigateBack();
			}
		}).catch(err => console.log(err))
	}
	
	const del = () => {
		uni.showModal({
			content:'确定要删除吗？'
		}).then(async res => {
			if(res.confirm) {
				uni.showLoading();
				const result = await api.delAddress(store.user.UserID,formData.value.AddressID);
				uni.hideLoading();
				await nextTick();
				if(result[1]) {
					uni.showToast({
						icon:'none',
						title:result[1]
					})
				} else {
					uni.showToast({
						icon:'success',
						title:'删除成功'
					})
					await uni.$u.sleep(800);
					uni.navigateBack();
				}
			}
		})
	}
</script>

<style>
</style>